package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    // 用户订单提交
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理异常情况
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook byId = addressBookMapper.getById(addressBookId);
        if (byId == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> byId1 = shoppingCartMapper.findById(userId);
        if (byId1 == null || byId1.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表中插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(byId.getPhone());
        orders.setConsignee(byId.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(byId.getProvinceName() + byId.getCityName() + byId.getDistrictName() + byId.getDetail());
        orders.setUserName(byId.getConsignee());
        orderMapper.insert(orders);

        //向订单详情表中插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : byId1) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertList(orderDetailList);



        //封装订单信息并返回订单信息
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime())
                .orderTime(orders.getOrderTime()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).build();
        return orderSubmitVO;

    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    @Transactional
    public void paySuccess(String outTradeNo) {
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo,userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //清空购物车
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        shoppingCartMapper.delete(shoppingCart);

        Map map = new HashMap();
        map.put("type",1);//1.来单提醒 2.客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    // 用户订单历史
    @Override
    public PageResult historyOrders(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
//        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> pageResult = orderMapper.historyOrders(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();
        if (pageResult.getTotal() >  0 && pageResult!=null) {
        for (Orders orders : pageResult) {
            Long id = orders.getId();
            List<OrderDetail> byId = orderDetailMapper.findById(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(byId);
            list.add(orderVO);
        }}
        return new PageResult(pageResult.getTotal(), list);
    }

    // 用户订单详情
    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> byId = orderDetailMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(byId);
        return orderVO;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders o = new Orders();
        o.setId(id);
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED){
            o.setPayStatus(Orders.REFUND);
        }
        o.setStatus(Orders.CANCELLED);
        o.setCancelReason("用户取消订单");
        o.setCancelTime(LocalDateTime.now());
        orderMapper.update(o);
    }

    //再来一单
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.findById(id);
        if (orderDetails == null || orderDetails.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<ShoppingCart> list = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            list.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(list);
    }

    @Override
    public void reminder(Long id) {
        Orders byId = orderMapper.getById(id);
        String content = byId.getNumber();
        Map map = new HashMap();
        map.put("type",2);//1.来单提醒 2.客户催单
        map.put("orderId",id);
        map.put("content","订单号:"+content);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    //商家订单搜索
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> pageResult = orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (pageResult.getTotal() > 0 && pageResult!= null) {
            for (Orders orders : pageResult) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                Long id = orders.getId();
                List<OrderDetail> byId = orderDetailMapper.findById(id);
                StringBuilder sb = new StringBuilder();
                for(OrderDetail orderDetail:byId){
                    String name = orderDetail.getName();
                    sb.append(name).append(",");
                }
                orderVO.setOrderDishes(sb.toString());
                list.add(orderVO);
            }
        }
        return new PageResult(pageResult.getTotal(), list);
    }

    //各个状态的订单数量统计
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Orders orders = new Orders();
        //待接单
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        Integer i = orderMapper.count(orders);
        orderStatisticsVO.setToBeConfirmed(i);
        //待派送
        orders.setStatus(Orders.CONFIRMED);
        i = orderMapper.count(orders);
        orderStatisticsVO.setConfirmed(i);
        //派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        i = orderMapper.count(orders);
        orderStatisticsVO.setDeliveryInProgress(i);
        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetails = orderDetailMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    //接单
    @Override
    public void updateStatusConfirm(Orders orders) {
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    //拒单
    @Override
    public void rejection(Orders orders) {
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelReason(orders.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    //商家取消订单
    @Override
    public void cancelByAdmin(Orders orders) {
        Orders byId = orderMapper.getById(orders.getId());
        if (byId.getStatus() == Orders.COMPLETED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelReason("商家取消订单:"+orders.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    //派送订单
    @Override
    public void delivery(Orders orders) {
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    //订单完成
    @Override
    public void complete(Orders orders) {
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

}
